package study.queue;


/**
 * @Classname LoopQueue
 * @Author happytaohaha
 * @Date 2020/3/27
 * @Description TODO
 */
public class LoopQueue<E> implements Queue<E> {

    private E[] data;

    private int front = -1;
    private int tail = -1;
    private int size;

    public LoopQueue(int capacity){
        //有一个做为标志不让 front = end
        data = (E[])new Object[capacity+1];

    }

    public LoopQueue(){
        this(10);
    }
    //删除标志位
    public int getCapacity(){
        return data.length -1 ;
    }

    @Override
    public int getSize() {
        return size;
    }

    @Override
    public boolean isEmpty() {
        return false;
    }

    @Override
    public void enqueue(E e) {
        if((tail+1)%data.length == front){
            //有意识地浪费了一个空间
            resize(getCapacity() * 2);
        }
        data[tail] = e;
        tail = (tail+1)%data.length;
        size++;
    }

    private void resize(int newCapacity) {
        E[] newData = (E[])new Object[newCapacity+1];
        for(int i = 0; i < size; i++ ){
            newData[i] = data[(front+i)%data.length];
        }
        data = newData;
        front = 0;
        tail = size;
    }

    @Override
    public E dequeue() {
        if(isEmpty()){
            throw new IllegalArgumentException("队列为空");
        }
        E ret = data[front];
        front = (front + 1)% data.length;
        size--;
        if(size == getCapacity() / 4 && getCapacity() / 2 != 0){
            resize(getCapacity() /2);
        }
        return ret;
    }


    @Override
    public E getFront() {
        if(isEmpty()){
            throw new IllegalArgumentException("队列为空");
        }
        return data[front];
    }

    @Override
    public String toString(){
        StringBuffer res = new StringBuffer();
        res.append("LoopQueue:");
        res.append("[");
        for(int i  = front ; i!= tail; i = (i+1)% data.length){
            res.append(data[i]);
            if((i+1)%data.length != tail ){
                res.append(", ");
            }
        }
        res.append("]  tail");
        return res.toString();
    }
}
